<div class="px-2 m-2">
    <i class="fa fa-bullhorn mr-2"></i>发布新任务
    <hr class="mt-1 mx-0 mb-2">
    
    <form id="form-create-task">
        <div class="form-row">
            <div class="form-group col-md-4 col-lg-3">
                <label for="name">标题<b class="text-danger ml-2">*</b></label>
                <input type="text" class="form-control" id="name" name="name" placeholder="最大32个字符" required>
            </div>                    
                    
            <div class="form-group col-md-4 col-lg-3">
                <label for="pid">选择项目<b class="text-danger ml-2">*</b></label>
                <select id="pid" name="pid" class="form-control" onchange="return get_members_of_proj($(this).val());">
                    {% for _, info in ipairs(projs) do %}
                    <option value="{{info.id}}">{{info.name}}</option>
                    {% end %}
                </select>
            </div>

            <div class="form-group col-md-3 col-lg-2">
                <label for="weight">优先级<b class="text-danger ml-2">*</b></label>
                <select id="weight" name="weight" class="form-control">
                    {% for idx, info in ipairs(weights or {}) do %}
                    <option value="{{idx}}" class="{{info.color}}">{{info.title}}</option>
                    {% end %}
                </select>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group col-md-3">
                <label for="assigned">指派成员<b class="text-danger ml-2">*</b></label>
                <select id="assigned" name="assigned" class="form-control" onchange='return record_last_select(this, "recent_assigned");'>
                </select>
            </div>

            <div class="form-group col-md-3">
                <label for="cooperator">协作者/测试人员<b class="text-danger ml-2">*</b></label>
                <select id="cooperator" name="cooperator" class="form-control" onchange='return record_last_select(this, "recent_cooperator");'>
                </select>
            </div>
        </div>

        <div class="form-row">
            <div class="form-group col-md-3">
                <label for="start-time">计划开始时间<b class="text-danger ml-2">*</b></label>
                <input type="text" class="form-control form-datetime" id="start-time" name="start_time" value="{{os.date('%F', os.time() + 24 * 3600)}}" required>
            </div>

            <div class="form-group col-md-3">
                <label for="end-time">计划结束时间<b class="text-danger ml-2">*</b></label>
                <input type="text" class="form-control form-datetime" id="end-time" name="end_time" value="{{os.date('%F', os.time() + 24 * 3600)}}" required>
            </div> 
        </div>

        <div class="form-group">
            <label>任务标签</label><br>
            {% for idx, info in ipairs(tags or {}) do %}
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="checkbox" name="tags[]" value="{{idx}}">
                <span class="badge {{info.color}} mr-1">{{info.title}}</span><span class="text-muted">{{info.desc}}</span>
            </div>
            {% end %}
        </div>

        <div class="form-group">
            <label for="content">任务描述</label>
            <textarea id="content" name="content" data-provide="markdown" rows="12" data-savable="false" data-iconlibrary="fa" data-upload="/dashboard/files/upload"></textarea>
        </div>

        <div class="form-group">
            <a href="#" class="btn-link" onclick="return add_attachment();"><i class="fa fa-upload mr-1"></i>上传附件</a>
            <div id="form-attachments" data-counter="0"></div>
        </div>

        <div class="form-group">
            <div id="err"></div>
        </div>

        <div class="mt-4">
            <button id="btn-create-commit" type="button" class="btn btn-primary">确认发布</button>
            <button type="button" class="btn btn-secondary" onclick="return quit_create();">取  消</button>
        </div>
    </form>
</div>

<script>
    
$('#form-create-task .form-datetime').datepicker({
    autoclose: true,
    format: 'yyyy-mm-dd'
});

$('#form-create-task #content').markdown();

function record_last_select(elem, key) {
    var recent = Cookies.getJSON(key);
    var val = parseInt($(elem).val());

    if(!recent || recent.length == 0) {
        recent = [val];
    } else {
        recent.splice(0, 0, val);
        $.unique(recent);
        if (recent.length > 3) recent.pop();
    }

    Cookies.set(key, recent, { expires: 365 });
}

function get_members_of_proj(pid) {
    $('#form-create-task #assigned').empty();
    $('#form-create-task #cooperator').empty();

    $.post('/dashboard/tasks/members_of_proj', {pid: pid}, function(ret) {
        var valid_assigned = $('<optgroup>', { label : "可指派人员" });
        var valid_cooperator = $('<optgroup>', { label : "可选人员" });

        $.each(ret, function(_, info) {
            var opt = $('<option>', { value: info.uid }).text('【' + info.user_role + '】' + info.user);
            if (info.role == 3) valid_assigned.append(opt);
            if (info.role == 4) valid_cooperator.append(opt.clone());
        });

        $.each(ret, function(_, info) {
            var opt = $('<option>', { value: info.uid }).text('【' + info.user_role + '】' + info.user);
            if (info.role != 3) valid_assigned.append(opt);
            if (info.role != 4) valid_cooperator.append(opt.clone());
        });

        $('#form-create-task #assigned').append(valid_assigned);
        $('#form-create-task #cooperator').append(valid_cooperator);

        var recent = Cookies.getJSON('recent_assigned');
        if(recent) {            
            var recent_assigend = $('<optgroup>', { label : "最近选择" });
            $.each(recent, function(_, id) {
                $('option[value="' + id + '"]', valid_assigned).appendTo(recent_assigend);
            });
            recent_assigend.insertBefore(valid_assigned);
        }

        recent = Cookies.getJSON('recent_cooperator');
        if(recent) {            
            var recent_cooperator = $('<optgroup>', { label : "最近选择" });
            $.each(recent, function(_, id) {
                $('option[value="' + id + '"]', valid_cooperator).appendTo(recent_cooperator);
            });
            recent_cooperator.insertBefore(valid_cooperator);
        }            
    }, 'json');
}

function add_attachment() {
    var counter = $('#form-attachments').data('counter');
    counter++;
    $('#form-attachments').data('counter', counter);

    var input = $('<input type="file" id="attachment_' + counter + '" name="attachment_' + counter + '" class="form-control" hidden>');
    input.click();
    input.change(function() {
        var file = input[0].files[0];
        var btn_rm = $(
            '<span id="attachment_label_' + counter + '" class="badge badge-secondary mr-2">' +            
            '<i class="fa fa-paperclip mr-1"></i>' +
            file.name +
            '<i class="fa fa-close ml-2" onclick="return del_attachment(' + counter + ');"></i>' +
            '</span>');

        $('#form-attachments').append(btn_rm);
        $('#form-attachments').append(input);
    });
}

function del_attachment(id) {
    $('#attachment_' + id).remove();
    $('#attachment_label_' + id).remove();
}

function quit_create() {
    last_filter_menu.click();
    $('input[type="file"]').remove();
}

$(document).ready(function() {
    get_members_of_proj($('#form-create-task #pid').val());
})

$('#btn-create-commit').click(function() {
    $.ajax({
        url: '/dashboard/tasks/do_create',
        type: 'POST',
        data: new FormData(document.getElementById('form-create-task')),
        dataType: 'json',
        processData: false,
        contentType: false,
        cache: false,
        success: function(rsp) {
            if (!rsp.ok) {
                show_error('#form-create-task #err', '发布任务失败', rsp.err_msg);
            } else {
                $('#form-create-task #err').empty();
                last_filter_menu.click();
            }
        }
    });
});
</script>